﻿package core.command
{
    import com.adobe.cairngorm.commands.ICommand;
    import com.adobe.cairngorm.control.CairngormEvent;
    import com.adobe.serialization.json.JSON;
    
    import core.business.CallBackStatus;
    import core.event.BaseEvent;
    import core.model.AppModel;
    
    import mx.resources.ResourceManager;
    import mx.rpc.AsyncToken;
    import mx.rpc.Responder;
    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
    import mx.rpc.http.HTTPService;


    public class BaseCommand implements ICommand
    {
        public var apiMethod:String = null;

        protected var model:AppModel = AppModel.getInstance();

        private var callbackFunction:Function = null;

        private var showBusy:Boolean = false;
        
        private var jsonData:Object;

        public function BaseCommand(method:String = null)
        {
            this.apiMethod = method;
        }

        public function execute(event:CairngormEvent):void
        {
            // 设置设回调函数
            var callbackFun:Function = BaseEvent(event).callbackFunction;
            if(callbackFun != null)
            {
                callbackFunction = callbackFun;
            }

            showBusy = BaseEvent(event).showBusy;
            if(showBusy)
            {
                //MaskManager.getInstance().show();
            }

            if(event.data == null)
            {
                event.data = {};
            }
            if(this.apiMethod != null)
            {
                event.data["method"] = this.apiMethod;
            }
            
            var responder:Responder = new Responder(onResult, onFault);
            var s:HTTPService = new HTTPService();
           	var token:AsyncToken = s.send(event.data);
           	token.addResponder(responder);
        }

        protected function onResult(event:ResultEvent):void
        {
        	jsonData = JSON.encode(event.target.data);
            callCallback(CallBackStatus.SUCCESS, jsonData);
            hideBusy();
        }

        protected function onFault(event:FaultEvent):void
        {
            hideBusy();
            callCallback(CallBackStatus.FAIL, event.fault);
        }

        private function hideBusy():void
        {
            if(showBusy)
            {
                //MaskManager.getInstance().hide();
            }
        }

        private function callCallback(type:String, data:Object):void
        {
            if(callbackFunction != null)
            {
                callbackFunction(type, data);
            }
        }

        private function getText(key:String):String
        {
            return ResourceManager.getInstance().getString('MainUI', key);
        }

    }
}